# 封装工具类
import pymysql
import traceback
import logging
import app
from bs4 import BeautifulSoup
import json


# 通用的断言工具方法
def common_assert(test_case, response, status_code, status, description=None):
    test_case.assertEqual(status_code, response.status_code)
    test_case.assertEqual(status, response.json().get("status"))
    if description is not None:
        test_case.assertIn(description, response.json().get("description"))


# 解析HTML数据
def parse_html(form):
    # 提取第三方接口所需的参数
    soup = BeautifulSoup(form, "html.parser")
    action = soup.form.get("action")
    logging.info(f"trust_reg action={action}")
    req_data = {}
    for input in soup.find_all("input"):
        print(input.get("name"), "   ", input.get("value"))
        req_data[input.get("name")] = input.get("value")
    print("req_data==", req_data)
    return action, req_data


# 数据库操作的工具类
class DBUtil:
    conn = None

    # 获取数据库连接
    @classmethod
    def get_conn(cls):
        if cls.conn is None:
            cls.conn = pymysql.connect(host="121.43.169.97", user="root", password="Itcast_p2p_20191228",
                                       database="czbk_member", port=3306)
        return cls.conn

    # 关闭数据库连接
    @classmethod
    def close_conn(cls):
        if cls.conn is not None:
            cls.conn.close()
            cls.conn = None

    # 查询一条数据
    @classmethod
    def get_one(cls, sql):
        logging.info(f"sql={sql}")
        conn, cursor, result = None, None, None
        try:
            # 获取数据库连接
            conn = cls.get_conn()
            # 获取游标对象
            cursor = conn.cursor()
            # 执行SQL
            cursor.execute(sql)
            # 获取查询结果
            result = cursor.fetchone()
        except Exception as e:
            logging.error(f"查询一条数据时出现异常！sql={sql}")
            # traceback.print_exc()
            logging.error(f"出现异常了：{e}")
            logging.exception("查询一条数据时出现异常：")
        finally:
            # 关闭游标
            if cursor is not None:
                cursor.close()
            # 关闭连接
            cls.close_conn()
        return result

    # 查询全部数据
    @classmethod
    def get_all(cls, sql):
        conn, cursor, result = None, None, None
        try:
            # 获取数据库连接
            conn = DBUtil.get_conn()
            # 获取游标对象
            cursor = conn.cursor()
            # 执行SQL
            cursor.execute(sql)
            # 获取查询结果
            result = cursor.fetchall()
        except:
            print(f"查询全部数据时出现异常！sql={sql}")
            traceback.print_exc()
        finally:
            # 关闭游标
            if cursor is not None:
                cursor.close()
            # 关闭连接
            DBUtil.close_conn()
        return result

    # 新增、修改、删除的操作
    @classmethod
    def update_insert_del(cls, sql):
        conn, cursor, result = None, None, None
        try:
            # 获取数据库连接
            conn = cls.get_conn()
            # 获取游标对象
            cursor = conn.cursor()
            # 执行SQL
            result = cursor.execute(sql)
            # 提交事务
            conn.commit()
        except:
            # 回滚事务
            conn.rollback()
            print(f"新增、修改、删除的时出现异常！sql={sql}")
            traceback.print_exc()
        finally:
            # 关闭游标
            if cursor is not None:
                cursor.close()
            # 关闭连接
            cls.close_conn()
        return result

    # 新增、修改、删除的操作-可以传入多个SQL，批量执行SQL
    @classmethod
    def update_insert_del2(cls, *sql_list):
        print("sql_list===", sql_list)
        conn, cursor, result = None, None, None
        try:
            # 获取数据库连接
            conn = cls.get_conn()
            # 获取游标对象
            cursor = conn.cursor()
            # 执行SQL
            for sql in sql_list:
                cursor.execute(sql)
            # 提交事务
            conn.commit()
        except:
            # 回滚事务
            conn.rollback()
            print(f"新增、修改、删除的时出现异常！sql_list={sql_list}")
            traceback.print_exc()
        finally:
            # 关闭游标
            if cursor is not None:
                cursor.close()
            # 关闭连接
            cls.close_conn()
        return result


# 读取测试数据文件，并组装成参数化要求的数据格式
# 格式：[(), (), ()]
def build_data(file_name):
    test_data = []
    with open(app.BASE_DIR + file_name, encoding="UTF-8") as f:
        json_data = json.load(f)
        for case_data in json_data:
            data = tuple(case_data.values())
            test_data.append(data)
    print("test_data==", test_data)
    return test_data


if __name__ == '__main__':
    # app.init_log_config()
    # r = DBUtil.get_one("select * from mb_member where6666 id=2")
    # print("r===", r)
    # r = DBUtil.get_all("select * from mb_member where id<100")
    # print("r===", r)

    # r = DBUtil.update_insert_del("update mb_member set email='hello@qq.com' where id=2")
    # print("r===", r)

    build_data("/data/login.json")
    pass
